const { exec } = require('child_process');
const submit = require('./utils/submit');
const region = require('./utils/reigon');
const gameType = require('./utils/gameType');
const cron = require('node-cron');
const os = require("os");
const iconv = require('iconv-lite');
const encoding = os.platform() == 'win32' ? 'cp936' : 'utf-8';
const binaryEncoding = 'binary';
let regionDetail = null;
let gameTypeEnum = null;
const config = require('./config')
const runExec = (cmd) => {
    return new Promise((resolve, reject) => {
        exec(cmd, { encoding: binaryEncoding }, function(error, stdout, stderr) {
            if (error) {
                reject(iconv.decode(Buffer.from(error.message, binaryEncoding), encoding));
            } else {
                resolve(iconv.decode(Buffer.from(stdout, binaryEncoding), encoding));
            }
        });
    })
}
function getRunningGames() {
  return new Promise(async (resolve, reject) => {
    const res = await runExec('tasklist /fo csv');
    const lines = res.trim().split('\n').slice(1);
      const games = lines
        .map(line => {
          const [name] = line.split(',')[0].split('"').filter(Boolean);
          return name;
        })
      const finalGames = new Set();
      games.forEach(game => {
        if (game === 'LeagueClient.exe') {
          finalGames.add(gameTypeEnum.LOL);
        } else if (game.includes('无畏契约')) {
          finalGames.add(gameTypeEnum.WuWeiQiYue);
        } else if (game.includes('Naraka')) {
          finalGames.add(gameTypeEnum.YongJie);
        } else if (game.includes('cs2.exe') || game.includes('cs.exe')) {
          finalGames.add(gameTypeEnum.CSGO);
        } else if (game.includes('TslGame.exe') || game.includes('ExecPubg.exe')) {
          finalGames.add(gameTypeEnum.JueDiQiuSheng);
        }
      })
      resolve(finalGames);
  });
}
// 每小时
const cronHourReg = '0 * * * *';
// 每分钟
const cronMinuteReg = '* * * * *';

async function start() {
  const gType = await gameType();
  if (gType.code === 200) {
    gameTypeEnum = gType.data;
  }
  const res = await region({
    departmentId: config.department_id,
    no: os.hostname()
  });
  if (res.code === 200) {
    regionDetail = res.data;
    console.log(regionDetail);
  }
  cron.schedule(cronHourReg, async () => {
    const games = await getRunningGames();
    console.log([...games]);
    const res = await submit({ games: [...games], detail: regionDetail })
  });
}

start()